Repository navigation
id: conversion-executor PoC — linked transfer pairs, write-ahead intent, recovery scanner (#2289) - #3873
Conversation
…nt, recovery scanner (#2289) PoC per #2289 from the #2063 conversion-engine design. Not the permanent feature (#2056 review-round rule). - ledger: TigerBeetle-shaped types, LedgerBackend seam, in-memory backend with TB semantics (atomic linked chains, idempotent transfer IDs, balance-invariant flags) - intent: write-ahead intent records (conversion id + pre-generated transfer IDs + amounts + authorisation id) persisted before submission; file-backed store with fsync + atomic rename - executor: LP pre-flight, one linked batch (T1 user->LP, optional fee leg, T3 LP->user), user_data_128 = conversion_id on all legs - recovery: scanner reconciles Recorded/Submitted intents by transfer-ID lookup (present = Posted; absent = resubmit same IDs or abandon) - harness: step-0 throwaway single-replica TigerBeetle test cluster, binary pinned to 0.17.9 (verified latest release), start/stop with an ignored smoke test Tests (standalone-verified on the laptop, same module/deps): 7 passed, 1 ignored — posted conversion findable by user_data_128, atomic failure moves nothing, crash recovery in both windows without double-posting, LP pre-flight rejection, file-store reopen recovery. CI (id-check) is the authoritative run for the in-tree build.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 26 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ead200f74e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let amount_out = request.quote.amount_out(request.amount_in); | ||
| if request.quote.denominator == 0 { | ||
| bail!("preflight: rate quote has a zero denominator"); |
There was a problem hiding this comment.
Check the denominator before calculating the output amount
When a request has a zero quote denominator, preflight calls amount_out before reaching the explicit validation, so integer division panics instead of returning the intended error. Move the denominator check ahead of the calculation so malformed quotes are rejected without terminating the caller.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b02ab96: preflight now checks the denominator before any calculation, and RateQuote::amount_out itself returns None on a zero denominator. Regression test: zero_denominator_quote_is_rejected_not_a_panic.
| } | ||
|
|
||
| impl RateQuote { | ||
| pub fn amount_out(&self, amount_in: u128) -> u128 { |
There was a problem hiding this comment.
Avoid silently saturating the rate calculation
When amount_in * numerator overflows, saturation silently changes the authorised exchange rate even if the final quotient fits in u128. For example, amount_in = 2 and numerator = denominator = u128::MAX should produce 2, but this calculation produces 1, which the executor can successfully post. Use overflow-safe multiply/divide arithmetic or return an explicit overflow error rather than submitting a conversion with an incorrect destination amount.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b02ab96: amount_out uses checked_mul and returns Option; every caller bails with an explicit overflow error instead of posting a saturated rate. Regression test: overflowing_quote_is_rejected_not_saturated.
| fs::rename(&tmp, &path)?; | ||
| Ok(()) |
There was a problem hiding this comment.
Sync the intent directory after renaming the record
On a machine crash or power loss, syncing the temporary file does not guarantee durability of the subsequent rename in the containing directory. Consequently, put can return successfully and permit ledger submission while the write-ahead intent's filename is still not durable; recovery may then lose the record needed to reconcile that submission. Sync the containing directory after the rename before returning success.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b02ab96: FileIntentStore::put now opens and sync_all's the containing directory after the rename, so the directory entry is durable before put returns.
| if let Ok(mut stream) = TcpStream::connect(&self.address) { | ||
| let _ = stream.write_all(b""); | ||
| let _ = stream.read(&mut [0u8; 1]); | ||
| return Ok(()); |
There was a problem hiding this comment.
Remove the unbounded read from the readiness probe
If the replica accepts the TCP connection but sends no unsolicited data, this blocking read never returns: the probe sends no protocol request and sets no read timeout. The surrounding 30-second deadline is therefore never checked again, so TestCluster::start and the ignored smoke test can hang indefinitely. Treat a successful connection as readiness, or use a bounded protocol-aware probe.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b02ab96: wait_ready treats a successful TCP connect as readiness and no longer reads from the socket, so the 30s deadline is enforceable.
| for (offset, transfer) in chain.iter().enumerate() { | ||
| match self.validate_and_stage(transfer, &mut staged) { |
There was a problem hiding this comment.
Reject duplicate transfer IDs within a staged chain
When two legs share a transfer ID, validation checks only committed transfers, so both legs stage their balance changes and return success. The later commit loop stores only the first leg under that ID, leaving posted balance movements absent from the transfer journal. This is reachable through ConversionRequest.transfer_ids, which has no uniqueness check, and was reproduced with two linked legs returning success but only one stored transfer. Track IDs during chain validation and reject duplicates before committing any balance changes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b02ab96: create_transfers tracks staged transfer IDs per chain and rejects a duplicate (Exists if identical, ExistsWithDifferentFields otherwise) before any balance change commits. Regression test: duplicate_transfer_id_in_one_chain_is_rejected.
| let present = record | ||
| .legs | ||
| .iter() | ||
| .filter(|leg| backend.lookup_transfer(leg.id).is_some()) |
There was a problem hiding this comment.
Verify transfer contents before marking an intent posted
When persisted transfer IDs collide with unrelated existing transfers, this existence-only check marks the conversion AlreadyPosted even though its requested legs never executed. For example, a prepared no-fee request using IDs 501 and 502 from the test fixture's funding transfers is incorrectly reconciled as posted. Compare each looked-up transfer with its persisted leg and report mismatches as inconsistent instead of treating ID presence as proof of posting.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b02ab96: the scanner counts a leg as posted only when the looked-up transfer equals the persisted leg; ID collisions with different contents are reported Inconsistent. Regression test: recovery_does_not_trust_transfer_id_existence_alone (your 501/502 fixture case).
| self.store | ||
| .put(&record) | ||
| .context("write-ahead intent persist failed")?; |
There was a problem hiding this comment.
Preserve the original intent when a conversion ID is reused
If a caller retries an existing conversion ID with newly generated transfer IDs, prepare unconditionally replaces its persisted intent because both stores implement put as insert-or-replace. After an earlier successful or outcome-unknown submission, the new IDs can post the same conversion again, while the original recovery record is erased. Look up the conversion ID before preparing a replacement and either reuse the original immutable legs or reject a conflicting request.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b02ab96: prepare looks up the conversion ID first - an identical retry reuses the persisted intent (state included), a conflicting one is rejected instead of replacing the record. Regression test: conversion_id_reuse_cannot_replace_persisted_intent.
| if let Some(error) = failed { | ||
| anyhow::bail!( | ||
| "recovery resubmission of conversion {} failed: {error:?}", | ||
| record.conversion_id | ||
| ); |
There was a problem hiding this comment.
Continue scanning after an individual resubmission is rejected
When a conversion becomes unfundable after preparation, as demonstrated by atomic_failure_moves_nothing, its resubmission encounters an ordinary ledger rejection and this bail! aborts recovery of every subsequent intent. The rejected record remains unresolved; with unchanged in-memory store contents, subsequent scans encounter records in the same order and repeatedly leave later valid or already-posted conversions unreconciled. Report the rejection per intent and continue scanning the remaining records.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b02ab96: a rejected resubmission now yields a per-record ResubmissionRejected outcome, leaves that record unresolved, and the scan continues with the remaining records. Regression test: recovery_scan_continues_after_a_rejected_resubmission.
#2289) - executor: amount_out is checked (zero denominator / overflow are explicit errors, never a panic or silent saturation); preflight checks the denominator before calculating - executor: prepare never replaces a persisted intent for a reused conversion ID - identical retries reuse it, conflicting ones bail - intent: FileIntentStore syncs the containing directory after the rename so the write-ahead record itself is durable - harness: readiness probe treats a successful TCP connect as ready; the unbounded read that defeated the 30s deadline is gone - ledger: duplicate transfer IDs within one staged chain are rejected (Exists / ExistsWithDifferentFields) before any staging - recovery: AlreadyPosted requires each looked-up transfer to equal the persisted leg, not just exist by ID - recovery: a rejected resubmission is reported per-record (ResubmissionRejected) and the scan continues Tests: 6 new regression tests; cargo test --lib currency_poc on the laptop: 13 passed, 0 failed, 1 ignored (live-cluster smoke).
…rsion-executor-poc # Conflicts: # pkgs/id/src/lib.rs
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b02ab96212
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| pub fn prepare(&mut self, request: &ConversionRequest) -> Result<IntentRecord> { | ||
| self.preflight(request)?; |
There was a problem hiding this comment.
Resolve existing intents before checking current balances
When a successful conversion leaves the user or LP unable to fund the same conversion again, an identical retry fails here before reaching the existing-intent lookup. For example, using the test fixture with amount_in = 10_000 and fee_amount = 0 posts successfully, but retrying that request fails because the user's spendable balance is now zero, despite its persisted intent already being Posted. This prevents callers from obtaining the successful result after a lost response. Check and validate the existing intent before applying funding preflight checks intended for a new conversion.
Useful? React with 👍 / 👎.
Implements the #2289 conversion-executor PoC (from the #2063 design). PoC only — not the permanent feature (program rule on #2056: review round first).
What's here (
pkgs/id/src/currency_poc/)harness.rs): throwaway single-replica TigerBeetle test cluster the suite can start/stop (sanctioned shape per the cluster-topology investigation). Binary pinned to 0.17.9 (verified latest release via the GitHub releases API) and version-checked before start; release-zip acquisition URL recorded in the module. Ignored smoke test:cargo test -p id currency_poc -- --ignored.ledger.rs): TigerBeetle-shapedAccount/Transfertypes and aLedgerBackendtrait, plus an in-memory backend implementing the TB semantics the executor depends on — atomic linked chains, idempotent transfer IDs (Existson identical resubmission), balance-invariant flags, cross-ledger rejection. Per the id: investigate: TigerBeetle — multi-currency ledgers, conversions, per-coin vs balance model, 3-node cluster topology #2040 investigation, the client choice for a real binding is the official Rust client; it can implement this same trait against the harness cluster.intent.rs): conversion ID + pre-generated transfer IDs + amounts + authorisation ID persisted (fsync + atomic rename in the file store) before any submission.executor.rs): LP pre-flight (accounts/ledgers, user covers amount+fee, LP destination inventory), then one linked batch — T1 user→LP (source ledger), optional fee leg, T3 LP→user (destination ledger) — every leg stampeduser_data_128 = conversion_id.recovery.rs): reconcilesRecorded/Submittedintents by transfer-ID lookup — all present ⇒ Posted; none present ⇒ resubmit the same byte-identical IDs (or abandon); partial ⇒ reported inconsistent, never guessed.Tests — #2063 §4 cases (
tests.rs)Standalone-verified on the laptop (module + same deps,
cargo test): 7 passed, 1 ignored (the ignored one is the real-cluster smoke test).user_data_128, balances move exactly oncelinked_event_failedCI (
id-check.yml) is the authoritative in-tree run; this PR parks in the queue awaiting it.Remaining / honest gaps
LedgerBackendbinding over the official Rust client yet, so the scenario suite runs against the TB-semantics in-memory backend, not a live replica. That binding is the natural follow-on once this PoC's shape is reviewed.Closes-in-part: #2289 acceptance items 1–2 are demonstrated by the test suite above (item 1 against the semantics backend; live-cluster demonstration pending the client binding); item 3 is the #2063 comment posted with this PR.
Need help on this PR? Tag
@codesmith-botwith what you need.